<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="400" destroy-on-close @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100px"
            style="width: 90%">
            <el-form-item label="组织机构" prop="orgIds">
                <el-cascader v-model="form.orgIds" :options="groups" :props="groupsProps" :show-all-levels="false"
                    :collapse-tags="true" clearable filterable style="width: 100%;" @change="orgChange"></el-cascader>
            </el-form-item>
            <el-form-item prop="roleIds" label="角色">
                <!-- <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%;" filterable>
                    <el-option v-for="item in options" :key="item.id" :label="item.orgName + '-' + item.roleName"
                        :value="item.id" />
                </el-select> -->
                <el-select-v2 v-model="form.roleIds" :options="options" placeholder="请选择角色" style="width: 100%;"
                    multiple filterable clearable :loading="selectLoading" :disabled="options.length <= 0" />
            </el-form-item>

        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
</template>

<script>
export default {
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "send",
            titleMap: {
                send: '批量分配角色'
            },
            visible: false,
            isSaveing: false,
            //表单数据
            form: {
                staffIds: [],
                roleIds: [],
                orgIds: []
            },
            options: [],
            groups: [],
            groupsProps: {
                value: "id",
                multiple: true,
                emitPath: false,
                checkStrictly: true
            },
            selectLoading: false
        }
    },

    mounted() {
        // this.getRoles()
        // this.getGroup()
    },
    methods: {
        // async getRoles() {

        // },
        //加载树数据
        async getGroup() {
            var res = await this.$API.basic.org.list.post({ data: {} });
            this.groups = res.data;
        },
        //显示
        open(mode = 'send') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        async submit() {
            var valid = await this.$refs.dialogForm.validate().catch(() => { })
            if (!valid) {
                return false
            }
            this.isSaveing = true;
            let req = this.form.staffIds.map((staffId) => {
                let item = {
                    staffId: staffId,
                    roleIds: this.form.roleIds,
                    orgIds: this.form.orgIds
                }
                return item
            })

            var res = await this.$API.basic.staff.batchAuth.post({ data: req });
            this.isSaveing = false;
            if (res.code == 0) {
                this.$emit('success', this.form, this.mode)
                this.visible = false;
                this.$message.success("操作成功")
            } else {
                this.$alert(res.message, "提示", { type: 'error' })
            }
        },
        //表单注入数据
        async setData(selection, groups) {
            let orgIds = []
            let staffIds = selection.map((item) => {
                orgIds = item.orgIds ? [...orgIds, ...item.orgIds.split(',').map(Number)] : orgIds
                return item.id
            })
            this.form.orgIds = [...new Set(orgIds)];
            selection.map((item) => {
                if (item.orgId) {
                    this.form.orgIds.push(item.orgId)
                }
            })
            console.log(this.form.orgIds)

            var res = await this.$API.basic.staff.roleListByIds.post({ data: { staffIds: staffIds } });
            if (res && res.code == 0) {
                this.form.roleIds = res.data
            }

            this.form.staffIds = staffIds
            this.groups = groups

            if (this.form.orgIds && this.form.orgIds.length > 0) {
                this.getOrgIds(this.form.orgIds)
            }
        },
        async getOrgIds(values) {
            this.selectLoading = true
            if (values.length <= 0) {
                this.options = []
            } else {
                var datas = await this.$API.basic.staff.orgRoles.post({
                    data: {
                        orgIds: values,
                        pageSize: 5000, pageNum: 1
                    }
                });
                if (datas && datas.code == 0) {
                    this.options = datas.data.map((item) => ({
                        label: item.orgName + ' - ' + item.roleName,
                        value: item.id
                    }))
                    //如果取消勾选了某个组织，应该也要从roleIds中删除对应组织的角色ID
                    this.form.roleIds = this.options
                        .filter(item => this.form.roleIds.includes(Number(item.value)))
                        .map(item => Number(item.value));
                }
            }
            this.selectLoading = false

            // this.selectLoading = true
            // let req = []
            // values.forEach(value => {
            //     const fullPath = this.findNodePath(this.groups, value);
            //     if (fullPath) {
            //         req = req.concat(fullPath);
            //     }
            // });

            // // 去重
            // req = Array.from(new Set(req.map(JSON.stringify))).map(JSON.parse);
            // let list = req.map((item) => {
            //     return item.id
            // })

            // if (list.length <= 0) {
            //     this.options = []
            // } else {
            //     var datas = await this.$API.basic.staff.orgRoles.post({
            //         data: {
            //             orgIds: values,
            //             pageSize: 5000, pageNum: 1
            //         }
            //     });
            //     if (datas && datas.code == 0) {
            //         this.options = datas.data.map((item) => ({
            //             label: item.orgName + ' - ' + item.roleName,
            //             value: item.id
            //         }))
            //     }
            // }
            // this.selectLoading = false

            // //如果取消勾选了某个组织，应该也要从roleIds中删除对应组织的角色ID
            // this.form.roleIds = this.options
            //     .filter(item => this.form.roleIds.includes(Number(item.value)))
            //     .map(item => Number(item.value));
        },
        // 查找节点路径（从根到当前节点）
        // findNodePath(tree, targetId, path = []) {
        //     for (const node of tree) {
        //         const currentPath = [...path, node];
        //         if (node.id == targetId) {
        //             return currentPath;
        //         }
        //         if (node.children && node.children.length > 0) {
        //             const result = this.findNodePath(node.children, targetId, currentPath);
        //             if (result) return result;
        //         }
        //     }
        //     return null;
        // },
        async orgChange(values) {
            this.getOrgIds(values)
        }
    }
}
</script>

<style></style>
